package io.afu.nginxhelper.utils;

import io.afu.nginxhelper.enums.ExceptionEnum;
import io.afu.nginxhelper.exceptions.NginxHelperException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author RffanLAB.方露宇
 * @version 0.1
 */
public class FileUtils {


    /**
     * 文件不存在检查
     * @param filePath 文件路径
     * @throws NginxHelperException 抛错
     */
    public static void checkExistance(String filePath) throws NginxHelperException {
        File file = new File(filePath);
        if (!file.exists()){
            throw new NginxHelperException(ExceptionEnum.FILE_NOT_FOUND);
        }
    }

    /**
     * 逐行读取Nginx 配置文件
     * @param filePath
     * @return
     * @throws NginxHelperException
     */
    public static List<String> readLines(String filePath) throws NginxHelperException{
        List<String> lines = new ArrayList<>();
        checkExistance(filePath);
        try {
            InputStream inputStream = new FileInputStream(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;
            while (true){
                str = reader.readLine();
                if (str != null){

                    str = str.trim();
                    str = str.replace("\n","");
                    if (!str.startsWith("#") && !str.equals("")){
                        lines.add(str);
                    }
                }else {
                    break;
                }
            }
            inputStream.close();
        }catch (Exception e){
            throw new NginxHelperException("读取文件出错");
        }
        return lines;
    }




}
